import React, { useState, useEffect, useRef } from 'react'
import { Button, Balloon, Input, Icon } from '@alifd/next'
import { translate } from '@/utils/tools'
import {
  ClockCircleOutlined,
  CloseCircleOutlined,
  LinkOutlined,
  SearchOutlined,
  CloudUploadOutlined,
  CopyOutlined,
  CheckCircleOutlined,
  StopOutlined,
  CloseSquareOutlined,
  MonitorOutlined,
  CloudOutlined,
  FileSearchOutlined,
  NodeIndexOutlined,
  LoadingOutlined,
  CloseOutlined,
  WarningOutlined
} from '@ant-design/icons'
import { useMemoizedFn } from 'ahooks'
import store from '@/store'
import styles from './index.module.scss'

const EyeButton = ({ mouse, treeKey, setEye, id }) => {
  const [graphState] = store.useModel('graph')
  const { idToEye, onlyToEye } = graphState

  const [opacity, setOpacity] = useState('0')
  useEffect(() => {
    setOpacity(mouse || idToEye.ids.includes(id) || onlyToEye.ids.includes(id) ? '1' : '0')
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [mouse, onlyToEye, idToEye, id, treeKey])
  return (
    <Button
      className={styles.button}
      style={{ opacity: opacity }}
      ghost="dark"
      type="normal"
      text
      onClick={() => setEye({ treeKey, type: 'idToEye' })}
    >
      {!idToEye.ids.includes(id) ? (
        <Icon className={styles.icon} type="eye" style={{ color: '#f5f5f5' }} />
      ) : (
        <Icon className={styles.icon} type="eye-close" style={{ color: '#1890ff' }} />
      )}
    </Button>
  )
}

const FavoritesButton = ({ mouse, treeKey, setEye, id }) => {
  const [graphState] = store.useModel('graph')
  const { idToEye, onlyToEye } = graphState

  const [opacity, setOpacity] = useState('0')
  useEffect(() => {
    setOpacity(mouse || idToEye.ids.includes(id) || onlyToEye.ids.includes(id) ? '1' : '0')
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [mouse, onlyToEye, idToEye, id, treeKey])
  return (
    <Button
      className={styles.button}
      style={{ opacity: opacity }}
      ghost="dark"
      type="normal"
      text
      onClick={() => setEye({ treeKey, type: 'onlyToEye' })}
    >
      {!onlyToEye.ids.includes(id) ? (
        <Icon className={styles.icon} type="favorites-filling" style={{ color: '#f5f5f5' }} />
      ) : (
        <Icon className={styles.icon} type="favorites-filling" style={{ color: '#1890ff' }} />
      )}
    </Button>
  )
}

const TitleDom = ({ name, id, updateBIMName, treeKey, treeType, setEye, textColor }) => {
  const [graphState] = store.useModel('graph')
  const { projectData } = graphState

  const [mouse, setMouse] = useState(false)
  const [click, setClick] = useState(false)
  const [value, setValue] = useState('')

  const definitionRef = useRef()
  const docRef = useRef()

  if (treeType === 'project') {
    docRef.current = projectData.docs[id]
    if (docRef.current) definitionRef.current = docRef.current.definition
  }

  useEffect(() => setValue(name ? translate(name || id) : id), [name, id])

  const createValue = useMemoizedFn(value => {
    if (docRef.current && definitionRef.current === 'storey') {
      const buildingId = docRef.current.building
      const building = projectData.docs[buildingId]
      const installmentId = building.installment
      const installment = projectData.docs[installmentId]
      const buildingName = building.name
      const installmentName = installment.name
      return installmentName + '-' + buildingName + '-' + value
    } else {
      return value
    }
  })

  const onBlur = () => {
    setClick(false)
    updateBIMName(value)
  }

  const createTooltip = useMemoizedFn((dom, text) => (
    <Balloon
      type={'normal'}
      trigger={dom}
      align="t"
      alignEdge
      delay={150}
      closable={false}
      offset={[8, 0]}
      needAdjust
      followTrigger
      children={text}
      shouldUpdatePosition
      popupClassName={styles.tooltip}
    />
  ))

  const createIcon = useMemoizedFn(() => {
    if (!docRef.current) return null
    let ugmId
    if (docRef.current.definition === 'storey') {
      ugmId = docRef.current.ugm
    } else if (docRef.current.definition === 'ugm') {
      ugmId = docRef.current.id
    }
    const ugm = projectData.docs[ugmId]
    if (!ugm) {
      const text = '待绑定'
      const icon = <LinkOutlined style={{ color: '#828282', fontSize: '16px', marginRight: '4px' }} />
      return createTooltip(icon, text)
    }
    let icon, text
    switch (ugm.taskState) {
      case '待处理':
        text = ugm.taskState
        icon = <ClockCircleOutlined style={{ color: '#2196F3', fontSize: '16px', marginRight: '4px' }} />
        break
      case '待审核':
        text = ugm.taskState
        icon = <SearchOutlined style={{ color: '#FFAE3F', fontSize: '16px', marginRight: '4px' }} />
        break
      case '待识图审核':
        text = ugm.taskState
        icon = <FileSearchOutlined style={{ color: '#FAD714', fontSize: '16px', marginRight: '4px' }} />
        break
      case '审核通过':
        text = ugm.taskState
        icon = <CheckCircleOutlined style={{ color: '#00C345', fontSize: '16px', marginRight: '4px' }} />
        break
      case '退回修改':
        text = ugm.taskState
        icon = <StopOutlined style={{ color: '#F52222', fontSize: '16px', marginRight: '4px' }} />
        break
      case '规划失败':
        text = ugm.taskState
        icon = <CloseCircleOutlined style={{ color: '#EB2F96', fontSize: '16px', marginRight: '4px' }} />
        break
      case '已识图':
        text = ugm.taskState
        icon = <MonitorOutlined style={{ color: '#C9E6FC', fontSize: '16px', marginRight: '4px' }} />
        break
      case '待复制规划结果':
        text = ugm.taskState
        icon = <CopyOutlined style={{ color: '#484848', fontSize: '16px', marginRight: '4px' }} />
        break
      case '待户型匹配':
        text = ugm.taskState
        icon = <NodeIndexOutlined style={{ color: '#FF9300', fontSize: '16px', marginRight: '4px' }} />
        break
      case '待上传':
        text = ugm.taskState
        icon = <CloudOutlined style={{ color: '#2196F3', fontSize: '16px', marginRight: '4px' }} />
        break
      case '上传中':
        text = ugm.taskState
        icon = <LoadingOutlined style={{ color: '#FAD714', fontSize: '16px', marginRight: '4px' }} />
        break
      case '已上传':
        text = ugm.taskState
        icon = <CloudUploadOutlined style={{ color: '#7500EA', fontSize: '16px', marginRight: '4px' }} />
        break
      case '上传失败':
        text = ugm.taskState
        icon = <CloseOutlined style={{ color: '#F52222', fontSize: '16px', marginRight: '4px' }} />
        break
      case '用户驳回修改':
        text = ugm.taskState
        icon = <CloseSquareOutlined style={{ color: '#2D46C4', fontSize: '16px', marginRight: '4px' }} />
        break
      case 'UGM去重失败':
        text = ugm.taskState
        icon = <WarningOutlined style={{ color: '#F52222', fontSize: '16px', marginRight: '4px' }} />
        break
      default:
        text = '待绑定'
        icon = <LinkOutlined style={{ color: '#828282', fontSize: '16px', marginRight: '4px' }} />
        break
    }
    return createTooltip(icon, text)
  })

  return (
    <div
      className={styles.titleDom}
      onMouseEnter={e => {
        setMouse(true)
        e.preventDefault()
      }}
      onMouseLeave={e => {
        setMouse(false)
        e.preventDefault()
      }}
    >
      {definitionRef.current === 'storey' || definitionRef.current === 'ugm' ? createIcon() : null}
      <div
        style={{ width: !click ? 'auto' : '150px', color: textColor || null }}
        onDoubleClick={e => {
          if (!click) setClick(true)
          e.preventDefault()
        }}
      >
        {click && (treeType === 'bim' || treeType === 'project') ? (
          <Input
            hasClear
            trim
            onBlur={onBlur}
            onChange={val => setValue(val)}
            autoFocus
            defaultValue={value}
            style={{ width: '100%' }}
            size="small"
          />
        ) : (
          createValue(value)
        )}
      </div>
      {treeType !== 'project' ? (
        <>
          &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
          <EyeButton mouse={mouse} treeKey={treeKey} setEye={setEye} id={id} />
          &nbsp;&nbsp;
          <FavoritesButton mouse={mouse} treeKey={treeKey} setEye={setEye} id={id} />
        </>
      ) : null}
    </div>
  )
}

export default TitleDom
